#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <chrono>

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "driver/gpio.h"

/**
 * Brief: button
 * This test code shows how to configure gpio and how to use gpio interrupt.
 *
 * GPIO9:  input, pulled up, interrupt from rising edge and falling edge
 *
 */
#define GPIO_INPUT_IO     9
#define GPIO_INPUT_PIN_SEL  1ULL<<GPIO_INPUT_IO
#define ESP_INTR_FLAG_DEFAULT 0

typedef void (*ButtonCallback)(void);

static xQueueHandle gpio_evt_queue = NULL;

static void IRAM_ATTR gpio_isr_handler(void* arg) {
    uint32_t gpio_num = (uint32_t) GPIO_INPUT_IO;
    xQueueSendFromISR(gpio_evt_queue, &gpio_num, NULL);
}

static void gpio_task_example(void* arg) {
    gpio_num_t io_num;
    ButtonCallback cb = (ButtonCallback)arg;
    static auto start = std::chrono::steady_clock::now();
    for(;;) {
        if(xQueueReceive(gpio_evt_queue, &io_num, portMAX_DELAY)) {
            printf("GPIO[%d] intr, val: %d\n", io_num, gpio_get_level(io_num));
            if (1 == gpio_get_level(io_num)) {   // key release
                auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();
                if(duration < 200) {
                    continue;
                } else {
                    cb();
                }
                start = std::chrono::steady_clock::now();
            } else {    // key down

            }
        }
    }
}

void init_button(ButtonCallback cb) {
    gpio_config_t io_conf = {}; //zero-initialize the config structure.
    //io_conf.intr_type = GPIO_INTR_POSEDGE; // 上升沿产生中断
    io_conf.intr_type = GPIO_INTR_ANYEDGE; // 上升、下降沿都产生中断
    io_conf.pin_bit_mask = GPIO_INPUT_PIN_SEL; //bit mask of the pins, use GPIO0 here
    io_conf.mode = GPIO_MODE_INPUT; //set as input mode
    io_conf.pull_up_en = GPIO_PULLUP_ENABLE; //enable pull-up mode
    gpio_config(&io_conf);
 
    //create a queue to handle gpio event from isr
    gpio_evt_queue = xQueueCreate(10, sizeof(uint32_t));
    //start gpio task
    xTaskCreate(gpio_task_example, "gpio_task_example", 2048, (void*)cb, 10, nullptr);

    //install gpio isr service
    gpio_install_isr_service(ESP_INTR_FLAG_DEFAULT);
    //hook isr handler for specific gpio pin
    gpio_isr_handler_add((gpio_num_t)GPIO_INPUT_IO, gpio_isr_handler, (void*) GPIO_INPUT_IO);

    printf("Minimum free heap size: %d bytes\n", esp_get_minimum_free_heap_size());
}